package com.dm.yyxr.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dm.yyxr.pojo.dto.ConsumptionDto;
import com.dm.yyxr.pojo.dto.ConsumptionnumView;
import com.dm.yyxr.pojo.dto.ConsumptionnumViewDto;
import com.dm.yyxr.pojo.dto.UserDto;
import com.dm.yyxr.service.ConsumptionlogService;
import com.dm.yyxr.service.UserService;
import com.dm.yyxr.utils.Result;
import jdk.nashorn.internal.ir.RuntimeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/consumptionlog")
@RestController
@CrossOrigin
/**
 * 用户用电表相关操作
 */
public class ConsumptionlogController {
    @Autowired
    ConsumptionlogService consumptionlogService;
    @Autowired
    UserService userService;

    //获取用电量视图分页数据并返回分页数据
    @PostMapping("/getConsumptionnumView")
    public Result<Object> getConsumptionnumView(@RequestBody ConsumptionnumViewDto consumptionDto){
        //获取用电量视图的分页数据
        Page<ConsumptionnumView> page = consumptionlogService.getConsumptionnumView(consumptionDto);
        return Result.ok(page);
    }

    @GetMapping("/consumption/{id}")
    public Result<Object>consumption(@PathVariable("id") Integer id,@RequestParam("month") String month){
        Date m = null;
        //将传入的 month 字符串截取前11位并解析为 yyyy-MM-dd 格式的日期对象 m
        try{
            m = new SimpleDateFormat("yyyy-MM-dd").parse(month.substring(0,11));
        }catch (Exception ex){
            System.out.println(ex.getMessage());
        }
        //根据用户ID和月份获取用电量列表
        List<ConsumptionDto> list =  consumptionlogService.getByIdAndMonth(id,m);
        Map<String,Object> map = new HashMap<>();
        map.put("consumptions",list);
        //根据区域ID和月份获取用电量
        Double total = consumptionlogService.getTotal(id,m);
        map.put("total",total);
        return Result.ok(map);
    }
}
